import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class RedisDemoHash {
    public static void main(String[] args) {
        // 1. 连接到 Redis 服务器上.
        JedisPool jedisPool = new JedisPool("tcp://127.0.0.1:8888");
        // 2. 从 Redis 连接池中取一个连接出来，并及时释放
        try(Jedis jedis = jedisPool.getResource()){
//            test1(jedis);
//            test2(jedis);
//            test3(jedis);
//            test4(jedis);
            test5(jedis);

        }
    }

    private static void test5(Jedis jedis) {
        System.out.println("hmset n hmget");
        jedis.flushAll();
        // hmset
        Map<String,String> map = new HashMap<>();
        map.put("f1","111");
        map.put("f2","222");
        map.put("f3","333");
        jedis.hmset("key",map);
        // hmget
        List<String> vals = jedis.hmget("key", "f1", "f2", "f3");
        System.out.println(vals);

    }

    private static void test4(Jedis jedis) {
        System.out.println("hkeys n hvals");
        jedis.flushAll();

        jedis.hset("key","f1","111");
        jedis.hset("key","f2","222");
        jedis.hset("key","f3","333");
        //hkeys
        Set<String> keys = jedis.hkeys("key");
        System.out.println(keys);
        //hvals
        List<String> vals = jedis.hvals("key");
        System.out.println(vals);


    }

    private static void test3(Jedis jedis) {
        System.out.println("hdel");
        jedis.flushAll();

        jedis.hset("key","f1","111");
        jedis.hset("key","f2","222");
        jedis.hset("key","f3","333");

        long hdel = jedis.hdel("key", "f1", "f2", "f4");
        System.out.println(hdel);

        boolean exists = jedis.hexists("key", "f1");
        System.out.println(exists);


    }

    private static void test2(Jedis jedis) {
        System.out.println("hexists");
        jedis.flushAll();

        jedis.hset("key","f1","111");
        Map<String,String> map = new HashMap<>();
        map.put("f2","222");
        map.put("f3","333");
        jedis.hset("key",map);
        // hexists
        boolean hexists = jedis.hexists("key", "f1");
        System.out.println(hexists);
        hexists = jedis.hexists("key", "f4");
        System.out.println(hexists);


    }

    private static void test1(Jedis jedis) {
        System.out.println("hset n hget");
        jedis.flushAll();

        //hset
        jedis.hset("key","f1","111");
        Map<String,String> map = new HashMap<>();
        map.put("f2","222");
        map.put("f3","333");
        jedis.hset("key",map);
        //hget
        String hget = jedis.hget("key", "f1");
        System.out.println(hget);
        hget = jedis.hget("key","f4");
        System.out.println(hget);

    }
}
